package com.lsfb.signln.Leave.AddLeave;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.lsfb.signln.Login.LoginActivity;
import com.lsfb.signln.R;
import com.lsfb.signln.Utils.KeyBordsUtils;
import com.lsfb.signln.Utils.LittleUtils;
import com.lsfb.signln.Utils.LsfbUtils;
import com.lsfb.signln.Utils.URLString;
import com.lsfb.signln.View.MyCamera;
import com.lsfb.signln.View.PickerScrollView;
import com.lsfb.signln.View.RecycleViewDivider;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.annotation.ContentView;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.net.HttpClient;
import com.zgscwjm.lsfbbasetemplate.utils.DensityUtils;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.T;
import com.zgscwjm.lsfbbasetemplate.view.titlebar.LsfbTitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 请假申请
 * Created by Administrator on 2018/1/29 0029.
 */
@ContentView(R.layout.aty_add_leave)
public class AddLeaveActivity extends LsfbActivity {

    /**
     * 请假类型
     */
    @ViewInject(R.id.aty_leave_text_type)
    private TextView text_type;

    @ViewInject(R.id.pickerscrlllview)
    private PickerScrollView pickerscrlllview; // 滚动选择器

    @ViewInject(R.id.picker_rel)
    private LinearLayout picker_rel;

    @ViewInject(R.id.btn_sure)
    private TextView btn_sure;

    private List<Pickers> list; // 滚动选择器数据

    /**
     * 开始时间1
     */
    @ViewInject(R.id.aty_leave_start_text1)
    private TextView start_text1;

    /**
     * 开始时间2
     */
    @ViewInject(R.id.aty_leave_start_text2)
    private TextView start_text2;

    /**
     * 结束时间1
     */
    @ViewInject(R.id.aty_leave_end_text1)
    private TextView end_text1;

    /**
     * 结束时间2
     */
    @ViewInject(R.id.aty_leave_end_text2)
    private TextView end_text2;

    /**
     * 请假天数
     */
    @ViewInject(R.id.aty_leave_text_day)
    private TextView text_day;

    /**
     * 请假事由
     */
    @ViewInject(R.id.et_reason)
    private EditText et_reason;

    /**
     * 图片
     */
    @ViewInject(R.id.aty_img_leave)
    private SimpleDraweeView img_leave;

    private String img_uri = null;

    /**
     * 封装好的照相机
     */
    private MyCamera camera;

    /**
     * uir存储
     */
    private Uri muri;

    /**
     * 审批人
     */
    @ViewInject(R.id.rv_leave_person)
    private RecyclerView rv_leave_person;
    private List<ApprovalPersonBean.PlistBean> plistDatas;
    private ApprovalPersonAdapter adapter;

    /**
     * 抄送
     */
    @ViewInject(R.id.rv_leave_copyTo)
    private RecyclerView rv_leave_copyTo;
    private List<ApprovalPersonBean.ClistBean> clistDatas;
    private CopyToPersonAdapter adapter_copy;

    private int days;
    private String dates;
    private String start_date = null;
    private String end_date = null;
    private String type_id = "0";

    /**
     * 用于更新主线程UI
     */
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case 1:
                    img_leave.setImageURI(Uri.parse(URLString.IMAGES + img_uri));
                    break;
                case 2:
                    T.showShort(getApplicationContext(), "上传失败");
                    break;
            }
        }
    };

    @Override
    public void initView() {
        LsfbTitleBar titleBar = LittleUtils.setsimpletitlebar(this, "免定位申请");
        TextView textView = LittleUtils.rightbtn(this, "提交");

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commitApply();
            }
        });
        titleBar.setRightView(textView, 0, 0, DensityUtils.dp2px(this, 10), 0);

        camera = new MyCamera() {
            @Override
            public void resultUri(Uri uri) {
                muri = uri;
            }
        };

    }

    /**
     * 提交请假申请
     */
    private void commitApply() {
        if (start_date == null || start_date.isEmpty()) {
            T.showShort(this, "请选择免定位时间");
            return;
        }

        HashMap hashMap = new HashMap();
        hashMap.put("startTime", start_date);
        hashMap.put("endTime", end_date);
        hashMap.put("content", et_reason.getText().toString());
        hashMap.put("countDays", String.valueOf(days));
        hashMap.put("type", type_id);
        if (img_uri != null) {
            hashMap.put("imgPath", img_uri);
        }
        hashMap.put("days", dates);
        new BaseInternet().getData(URLString.COMMITLEAVEAPPLY, hashMap, String.class, new CommitLeaveEvent<String>(), true);
    }

    @EventAnnotation
    public void eventResult(CommitLeaveEvent<String> event) {
        switch (event.getCode()) {
            case 200:
                T.showShort(this, "提交申请成功");
                this.finish();
                break;
            case 1006:
                T.showShort(this, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(this);
                startActivity(new Intent(this, LoginActivity.class));
                break;
            default:
                T.showShort(this, event.getMsg());
                break;
        }
    }

    @Override
    public void initEvent() {

    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.aty_leave_type, R.id.aty_img_leave, R.id.aty_leave_select_time, R.id.btn_sure, R.id.layout_view})
    public void onClick(View view) {
        switch (view.getId()) {
            //请假类型
            case R.id.aty_leave_type:
//                Intent intent = new Intent(AddLeaveActivity.this, LeaveTypeActivity.class);
//                startActivityForResult(intent, 0);
                picker_rel.setVisibility(View.VISIBLE);
                KeyBordsUtils.closeKeybord(et_reason, getApplicationContext());
                break;
            case R.id.btn_sure:
                picker_rel.setVisibility(View.GONE);
                break;
            //选择请假时间
            case R.id.aty_leave_select_time:
                startActivityForResult(new Intent(this, LeaveSelectDateActivity.class), 1);
                break;
            //点击选择图片
            case R.id.aty_img_leave:
//                img_leave.setImageURI(URLString.UPLOAD);
                camera.show(this, this);
                break;
            case R.id.layout_view:
                picker_rel.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void initData() {
        list = new ArrayList<>();
        String[] type = new String[]{"因事", "因病", "年休", "其他"};
        for (int i = 0; i < type.length; i++) {
            list.add(new Pickers(type[i], String.valueOf(i)));
        }
        // 设置数据，默认选择第一条
        pickerscrlllview.setData(list);
        pickerscrlllview.setSelected(0);
        // 滚动选择器选中事件
        pickerscrlllview.setOnSelectListener(new PickerScrollView.onSelectListener() {
            @Override
            public void onSelect(Pickers pickers) {
                type_id = pickers.getShowId();
                text_type.setText(pickers.getShowConetnt());
            }
        });


        plistDatas = new ArrayList<>();
        adapter = new ApprovalPersonAdapter(this, plistDatas, R.layout.item_leave_person);
        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setOrientation(LinearLayoutManager.HORIZONTAL);
        RecycleViewDivider di = LsfbUtils.getHORIZONTALLineDivider(this, R.color.white_color, 30);
        rv_leave_person.setLayoutManager(layout);
        rv_leave_person.addItemDecoration(di);
        rv_leave_person.setAdapter(adapter);     //绑定adapter

        clistDatas = new ArrayList<>();
        adapter_copy = new CopyToPersonAdapter(this, clistDatas, R.layout.item_leave_person);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        RecycleViewDivider divider = LsfbUtils.getHORIZONTALLineDivider(this, R.color.white_color, 30);
        rv_leave_copyTo.setLayoutManager(layoutManager);
        rv_leave_copyTo.addItemDecoration(divider);
        rv_leave_copyTo.setAdapter(adapter_copy);     //绑定adapter

    }

    /**
     * 得到将要审批的人
     */
    private void getWillProcess() {
        HashMap hashMap = new HashMap();
        hashMap.put("day", String.valueOf(days));
        new BaseInternet().getData_Get(URLString.GETWILLPROCESS, hashMap, ApprovalPersonBean.class, new ApprovalPersonEvent<ApprovalPersonBean>(), true, false);
    }

    @EventAnnotation
    public void eventResult(ApprovalPersonEvent<ApprovalPersonBean> event) {
        switch (event.getCode()) {
            case 200:
                if (event.getData().getPlist() != null && !event.getData().getPlist().isEmpty()) {
                    plistDatas.clear();
                    plistDatas.addAll(event.getData().getPlist());
                    adapter.notifyDataSetChanged();
                    rv_leave_person.setVisibility(View.VISIBLE);
                }
                if (event.getData().getClist() != null && !event.getData().getClist().isEmpty()) {
                    clistDatas.clear();
                    clistDatas.addAll(event.getData().getClist());
                    adapter_copy.notifyDataSetChanged();
                    rv_leave_copyTo.setVisibility(View.VISIBLE);
                }
                break;
            case 1006:
                T.showShort(this, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(this);
                startActivity(new Intent(this, LoginActivity.class));
                break;
            default:
                T.showShort(this, event.getMsg());
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
//            case 0: //请假类型
//                if (data == null) {
//                    return;
//                } else {
//                    String datas = data.getStringExtra("datas");
//                    type_id = data.getIntExtra("id", 0);
//                    text_type.setText(datas);
//                }
//                break;
            case 1: //请假时间
                if (data == null) {
                    return;
                } else {
                    //请假天数
                    days = data.getIntExtra("days", 0);
                    text_day.setText(days + "天");

                    /**
                     * 得到将要审批的人
                     */
                    getWillProcess();

                    //请假具体日期
                    dates = data.getStringExtra("dates");

                    //开始时间
                    start_date = data.getStringExtra("start_date");
                    start_text1.setText(start_date.substring(5, 7) + "月" + start_date.substring(8, 10) + "日");
                    start_text1.setTextColor(getResources().getColor(R.color.theme_color));
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.YEAR, Integer.parseInt(start_date.substring(0, 4)));//指定年份
                    calendar.set(Calendar.MONTH, Integer.parseInt(start_date.substring(5, 7)) - 1);//指定月份 Java月份从0开始算
                    start_text2.setTextColor(getResources().getColor(R.color.theme_color));
                    //获取指定年份月份中指定某天是星期几
                    calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(start_date.substring(8, 10)));  //指定日
                    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                    switch (dayOfWeek) {
                        case 1:
                            start_text2.setText("星期日");
                            break;
                        case 2:
                            start_text2.setText("星期一");
                            break;
                        case 3:
                            start_text2.setText("星期二");
                            break;
                        case 4:
                            start_text2.setText("星期三");
                            break;
                        case 5:
                            start_text2.setText("星期四");
                            break;
                        case 6:
                            start_text2.setText("星期五");
                            break;
                        case 7:
                            start_text2.setText("星期六");
                            break;
                    }

                    //结束时间
                    end_date = data.getStringExtra("end_date");
                    end_text1.setText(end_date.substring(5, 7) + "月" + end_date.substring(8, 10) + "日");
                    end_text1.setTextColor(getResources().getColor(R.color.theme_color));
                    Calendar calendar2 = Calendar.getInstance();
                    calendar2.set(Calendar.YEAR, Integer.parseInt(end_date.substring(0, 4)));//指定年份
                    calendar2.set(Calendar.MONTH, Integer.parseInt(end_date.substring(5, 7)) - 1);//指定月份 Java月份从0开始算
                    end_text2.setTextColor(getResources().getColor(R.color.theme_color));
                    //获取指定年份月份中指定某天是星期几
                    calendar2.set(Calendar.DAY_OF_MONTH, Integer.parseInt(end_date.substring(8, 10)));  //指定日
                    int day_Week = calendar2.get(Calendar.DAY_OF_WEEK);
                    switch (day_Week) {
                        case 1:
                            end_text2.setText("星期日");
                            break;
                        case 2:
                            end_text2.setText("星期一");
                            break;
                        case 3:
                            end_text2.setText("星期二");
                            break;
                        case 4:
                            end_text2.setText("星期三");
                            break;
                        case 5:
                            end_text2.setText("星期四");
                            break;
                        case 6:
                            end_text2.setText("星期五");
                            break;
                        case 7:
                            end_text2.setText("星期六");
                            break;
                    }
                }
                break;

            case MyCamera.REQUESTCODE:
                if (resultCode == RESULT_OK) {
                    LsfbLog.e(muri.toString());
                    camera.crop(muri, 300);
                }

                break;
            case MyCamera.SYSTEMPHOTOS:
                if (resultCode == RESULT_OK) {
                    LsfbLog.e(data.getData().toString());
                    String url = "file://" + MyCamera.getPath(this, data.getData());
                    muri = Uri.parse(url);
                    camera.crop(muri, 300);
                }
                break;
            case MyCamera.CROPIMG:
                if (resultCode == RESULT_OK) {
                    LsfbLog.e("---------------------------------------------:" + muri.getPath());
//                    File file = new File(muri.getPath());

                    List<File> list = new ArrayList<>();
                    list.add(new File(muri.getPath()));

                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("img", muri.getPath());
                    // TODO: 2017/4/26 0026 token------
                    new HttpClient().postFile(URLString.UPLOAD, hashMap, list, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                            LsfbLog.e("上传失败" + e.getMessage());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            LsfbLog.e("上传success");
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response.body().string());
                                LsfbLog.e("上传结果" + jsonObject.toString());
                                if (jsonObject.getInt("code") == 200) {
                                    LsfbLog.e("得到回调");
                                    String img = jsonObject.getString("data");
                                    img_uri = img;
                                    handler.sendEmptyMessage(1);
                                } else {
                                    LsfbLog.e("得到回调失败");
                                    handler.sendEmptyMessage(2);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                break;
        }
    }

    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (this.getCurrentFocus() != null) {
                if (this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }
}
